<?php

declare(strict_types=1);

namespace Service\ChannelService;

use App\Model\BbcModel\ChannelWx;
use App\Model\BbcModel\ConfigChannel;
use Service\BaseService;
use Service\Code\Normal;
use Service\ExtraService\TaskWorker;

class ChannelWxService extends BaseService
{
    /**
     * 查询微信小程序配置
     * @param int $cid
     */
    public function queryWxConfig(int $cid)
    {
        return ChannelWx::instance()->info(['cid' => $cid]);
    }

    /**
     * $cid
     * @param [type] $cid
     * @return array
     */
    public function getMnApp($cid, $mnid)
    {
        if (empty($cid)) {
            return Normal::returnCode(Normal::FAIL, '没有渠道id');
        }
        $data = ConfigChannel::instance()->info(['cid' => $cid, 'code' => 'wxmnapp_pay']);
        if (empty($data) || empty($data['value'])) {
            return Normal::returnCode(Normal::FAIL, '没有相关小程序参数');
        }
        $value = json_decode($data['value'], true);

        $appInfo = [];
        if ($mnid == 2) {
            $appInfo['appid'] = $value['appid'] ?? '';
            $appInfo['appsecret'] = $value['appsecret'] ?? '';
        } else {
            $appInfo['appid'] = $value['cappid'] ?? '';
            $appInfo['appsecret'] = $value['cappsecret'] ?? '';
        }
        $appInfo['mch_id'] = $value['mch_id'] ?? '';
        $appInfo['key'] = $value['key'] ?? '';
        $appInfo['cert'] = $value['cert'] ?? '';
        $appInfo['cid'] = $param['cid'] ?? '';
        if (empty($appInfo['appid']) || empty($appInfo['appsecret'])) {
            return Normal::returnCode(Normal::FAIL, '没有相关小程序参数');
        }
        return Normal::returnCode(Normal::SUC, '请求成功', [
            'code' => 'miniapp_pay',
            'value' => $appInfo
        ]);
    }

    /**
     * 获取渠道的money
     */
    public static function getChannelMoney(array $param = [])
    {
        if (!isset($param['channel_id']) || empty($param['channel_id'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        $res = self::getYcData('QueryAccount', ['channel_id' => $param['channel_id']], $param['channel_id']);
        if ($res['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $res['msg']);
        }
        $money      = $res['data']['info']['balance'] ?? 0;
        $warn_money = $res['data']['info']['settlement_warn_money'] ?? 0;
        return Normal::returnCode(Normal::SUC, '获取成功', ['money' => round($money + $warn_money, 2), 'show_money' => $money]);
    }

    /**
     * 请求云仓获取数据
     */
    public static function getYcData($method, $requestdata, $cid)
    {
        $info = ChannelWx::where('cid', $cid)->first();
        if (!$info) {
            return Normal::returnCode(Normal::FAIL, '渠道不存在');
        }
        $request = [
            'appid'         => $info['stb_app_id'],
            'requestMethod' => $method,
            'requestData'   => rawurlencode(json_encode($requestdata)),
        ];
        ksort($request);
        $key             = $info['stb_app_secret'];
        $sign            = strtoupper(md5(getSignContent($request) . '&key=' . $key));
        $request['sign'] = $sign;
        $parameter       = [
            [
                'tag'    => 'channelWx_get_yc_data',
                'url'    => $info['stb_url'],
                'data'   => $request,
                'method' => 'post',
                'format' => 'x-www-form-urlencoded',
                'header' => [],
            ],
        ];
        $resTask         = TaskWorker::instance()->addTask($parameter);
        $resTask         = current($resTask);
        $response        = @json_decode($resTask['response']['result'], true);
        if ($response['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $response['msg'] ?? '请求错误');
        }
        return Normal::returnCode(Normal::SUC, '请求成功', $response['data']);
    }
}
